Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

524
Views
Passing float[] from C++ to Java using JNI

I am attempting to "pass" (i.e. copy) a raw float array from C++ to Java. The C++ structure holding the source array:

struct foo_cpp {
    float a[16];
};

The Java class holding the destination array:

public class foo_java {
    public float a[];

    public foo_java() {
        a = new float[16];
    }
}

The C++ function trying to pass the data to the Java class:

extern "C" JNIEXPORT jobject JNICALL Java_com_example_myapp_Controller_process_1frame(JNIEnv *env, jclass clazz)
{
    // C++ "source array"
    foo_cpp fc;
    // Initialize fc.a here...

    // Convert from cpp to java
    jobject foo_object;
    {
        // Create the foo object
        jclass foo_class_id = env->FindClass("com/example/myapp/foo_java");
        jmethodID foo_ctor_id = env->GetMethodID(foo_class_id, "<init>", "()V");
        foo_object = env->NewObject(foo_class_id, foo_ctor_id);

        // Get the field ID
        jfieldID field_id = env->GetFieldID(foo_class_id, "a", "[F");

        // Set the fields
        {
            // Get pointer to Java object float array (Get pointer to Java class foo_java::a)
            jobject field_data = env->GetObjectField(foo_object, field_id);
            jfloatArray *fa = reinterpret_cast<jfloatArray*>(&field_data);
            float *fa_raw = env->GetFloatArrayElements(*fa, nullptr);
            for (int i = 0; i < 16; i++)
                fa_raw[i] = static_cast<float>(fc.a[i]);
        }
    }
    
    return foo_object;
}

However, when running this, the values in the java object are not as expected.

What am I missing / doing wrong?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

The code mentioned in the question turned out to work as expected. The float values where correct and it was a classic case of misinterpretation / layered problems.

However, as @Michael pointed out in the comment: A call to ReleaseFloatArrayElements() is necessary to prevent leaking memory.

I've created a blog post regarding this: https://blog.insane.engineer/post/cpp_length_prefixed_strings/

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!